import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react';
import TreeList, { Column, Editing, Item, Toolbar } from 'devextreme-react/tree-list';
import { useModel } from 'umi';
import { getWindowsMapsList, intl } from '@/utils';
import { getCurrentZcbfInfo, getIsCheckProjectIsOpened, getLocalProjectList, getZcbfList, replaceFullSpace } from '../service';
import InitializePopup from '../../components/InitializePopup';
import notify from 'devextreme/ui/notify';
import './index.less'
import PubSub from 'pubsub-js';
import getApiData from '@/services/cpasRequest';
import { CpasIcon } from '~/public/cpas-ui';
import InputOKDialog from '../../components/InputOKDialog';
import LoadIndicator from 'devextreme-react/load-indicator';
import { Checkbox, Popover, Typography } from 'antd';
import { fixTreeData } from '../../tools';
import Button from 'devextreme-react/button';
import '@/pages/components/StyleFile/btnStyle.less';
import { ConvertOnlineButton } from '../ConvertOnline/ConvertOnlineButton';
import { CellDblClickEvent, RowDblClickEvent } from 'devextreme/ui/tree_list';
import DataSource from 'devextreme/data/data_source';

const { Text } = Typography;


const ZcbfTreeList = React.forwardRef((props: any, ref: any) => {
  const { tableRow } = props;
  const { initialState } = useModel('@@initialState');
  const { curUser } = initialState || {};
  const [treeData, setTreeData] = useState<any>([]);
  const initializePopupRef = useRef<any>();
  const refsInputDialog = useRef<any>();
  const [showSpin, setShowSpin] = useState<boolean>(false);
  const treeListRef = useRef<any>();

  const [selectedRows, setSelectedRows] = useState<any>([]);
  const [selectedRowsName, setSelectedRowsName] = useState<any>([]);

  const [treeDataMinate, setTreeDataMinate] = useState<any>(0);
  const [showConvertOnline, setShowConvertOnline] = useState<boolean>(false);
  const [localProjectList, setLocalProjectList] = useState<any[]>([]); //单机项目列表
  const [localProjectMap, setLocalProjectMap] = useState<any>({}); //单机项目列表,{sjxmbh:displayText}
  //const [disabledConvertOnline, setDisabledConvertOnline] = useState<boolean>();
  // const [disabledConvertHint, setDisabledConvertHint] = useState<string>('');

  const onTableTreeSelection = useCallback((rowsDataID: string[], rowsDataName: string[]) => {
    const zcbfIDString = rowsDataID.map((itemMap: any) => itemMap);
    const zcbfsName = rowsDataName.map((itemMap: any, indexMap: number) => {
      if (indexMap > 1) {
        return '';
      }
      return itemMap;
    });
    const zcbfsNameLength = zcbfIDString.length;
    PubSub.publish('zcbfidsInfoTreeList', { msg: 'zcbfidsInfo', data: { zcbfIDString, zcbfsName, zcbfsNameLength, projectBh: tableRow.projectBh } });
  }, []);

  const getZcbfListData = useCallback(async (isReload: boolean = false) => {
    if (!tableRow.sjxmbh) return;
    setShowSpin(true);
    const res = await getZcbfList({
      projectBh: tableRow.sjxmbh
    });
    if (res.success) {
      if (!isReload && selectedRows.length !== 0) {
        setSelectedRows([]);
        setSelectedRowsName([]);
        onTableTreeSelection([], []);
      }
      let selectedID: any = [];
      res.data.forEach((item: any) => {
        if (item.zcbfzt === 1) {
          selectedID.push(item.zcbfid);
        }
      });
      const fixData = fixTreeData(res.data, 'zcbfid', 'pzcbfID');
      setTreeData(fixData);
      setTreeDataMinate(selectedID.length);
      if (tableRow.XMType === "联机审计项目") {
        PubSub.publish('localTreeData', { msg: 'localTreeDataArr', data: res.data });
      }
      treeListRef.current.instance.clearFilter();
    } else {
      notify({ message: `请求报错：${res.data}`, position: 'top center' }, "error", 1000);
    }
    setShowSpin(false);
    if (tableRow.XMType === "联机审计项目") {
      loadLocalProjectList();//加载单机项目列表
    }
  }, [tableRow, curUser])

  const delButtonClick = async (rowData: any) => {
    const mapsData = getWindowsMapsList(rowData.zcbfid);
    if (mapsData) return notify({ message: `该项目已被打开，请勿删除！`, position: 'top center', width: 300 }, "warning", 2000);
    const res = await getIsCheckProjectIsOpened({ zcbfid: [rowData.zcbfid] });
    if (res.success) {
      if (res.data) {
        notify({ message: `该项目已被打开，请勿删除！`, position: 'top center', width: 300 }, "warning", 2000);
      } else {
        if (tableRow.XMType === "联机审计项目") {
          refsInputDialog.current.show({ zcbfid: rowData.zcbfid }, rowData.zcbfName, []);
        } else {
          refsInputDialog.current.show({ projectBh: tableRow.projectBh }, rowData.zcbfName, [tableRow.projectBh]);
        }
      }
    }

  };
  //加载单机项目列表
  function loadLocalProjectList() {
    //单机审计项目
    getLocalProjectList().then((data: any) => {
      setLocalProjectList(data);
      data.forEach((item: any) => localProjectMap[item.zcbfid] = item.displayText);
    });
  }
  useEffect(() => {
    if (!tableRow.sjxmbh) {
      setSelectedRows([]);
      setSelectedRowsName([]);
      onTableTreeSelection([], []);

      return setTreeData([]);
    }
    getZcbfListData();
  }, [tableRow]);

  useImperativeHandle(ref, () => ({
    // 树节点的刷新
    reloadButtonClick: () => {
      getZcbfListData();
    }
  }));

  PubSub.unsubscribe('zcbfidsTreeRefresh');
  PubSub.subscribe('zcbfidsTreeRefresh', async (msg: any, data: any) => {
    if (data.msg === 'zcbfidsRefresh') {
      getZcbfListData();
    }
  });

  const dblClickSkip = async (rowData: any) => {
    const zcbfInfo = await getCurrentZcbfInfo({ zcbfID: rowData.zcbfid })
    if (zcbfInfo.success) {
      if (tableRow.XMType === "联机审计项目") {
        const res = await getApiData('pm.getPermes', {
          projectBh: rowData.sjxmbh,
          usercode: curUser?.usercode,
          zcbfid: rowData.zcbfid
        });
        if (res.ok) {
          if (res.data && res.data.cnt > 0) {
            window.location.href = `cpas://openApp/?appName=cpas-audit&workbenchBtnId=${"tabWebappBtn_" + rowData.zcbfid}&params=${JSON.stringify(zcbfInfo.data)}&apicall=true`;
          } else {
            notify({ message: '您不是该项目组成员，不能打开该项目！', position: 'top center' }, "warning", 2000);
          }
        } else {
          notify({ message: res.data, position: 'top center' }, "error", 2000);
        }
      } else {
        window.location.href = `cpas://openApp/?appName=cpas-audit&workbenchBtnId=${"tabWebappBtn_" + rowData.zcbfid}&params=${JSON.stringify(zcbfInfo.data)}&apicall=true`;
      }
    } else {
      notify({ message: '获取当前zcbf信息失败！', position: 'top center' }, "error", 2000);
    }

  }

  const renderGridCell = (data: any) => {
    let textZcbfID: any = '';
    if (data.zcbfzt === 0) {
      textZcbfID = <span style={{ color: "#ddd" }}>
        {data.zcbfid}
      </span>
    } else if (data.zcbfzt === 1) {
      textZcbfID = <span >
        {data.zcbfid}
      </span>
    } else {
      textZcbfID = <span style={{ color: "#E92841" }}>
        {data.zcbfid}
      </span>
    }
    return (
      <div style={{ width: '100%', cursor: 'pointer' }} >
        {/* style={{ display: 'flex', alignItems: 'center', justifyContent: 'left', width: '100%' }} */}
        <Checkbox
          className='handWritingCheckBox'
          style={{ margin: '0px  7px' }}
          disabled={data.zcbfzt !== 1}
          checked={selectedRows.indexOf(data.zcbfid) !== -1}
          onChange={(e) => {
            const isChecked = e.target.checked;
            const dataId = data.zcbfid;
            const dataName = data.zcbfName;
            let selectedID: any = [];
            let selectedZcbfName: any = [];

            if (isChecked && selectedRows.indexOf(dataId) === -1) {
              selectedID = [...selectedRows, dataId];
              selectedZcbfName = [...selectedRowsName, dataName];
            } else if (!isChecked && selectedRows.indexOf(dataId) !== -1) {
              selectedID = selectedRows.filter((zcbfid: any) => zcbfid !== dataId);
              selectedZcbfName = selectedRowsName.filter((zcbfName: any) => zcbfName !== dataName);
            }
            setSelectedRows(selectedID);
            setSelectedRowsName(selectedZcbfName);
            onTableTreeSelection(selectedID, selectedZcbfName);
          }}
        />
        {/* <div style={{ width: '100%', textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>  </div> */}
        {/* <Popover content={textZcbfID} placement="bottom">
            {textZcbfID}
          </Popover> style={{ flex: 1 }} */}

        <Text ellipsis={{ tooltip: textZcbfID }}>
          {textZcbfID}
        </Text>

      </div>


    )
  }

  const renderGridCellName = (data: any) => {
    let textZcbfName: any = '';
    if (data.zcbfzt === 0) {
      textZcbfName = <span style={{ color: "#ddd" }}>
        【{data.zcbfName}】
      </span>
    } else if (data.zcbfzt === 1) {
      textZcbfName = <span >
        【{data.zcbfName}】
      </span>
    } else {
      textZcbfName = <span style={{ color: "#E92841" }}>
        【{data.zcbfName}】
      </span>
    }
    return (
      <div style={{ width: '100%', cursor: 'pointer' }} >
        <Text ellipsis={{ tooltip: textZcbfName }}>
          {textZcbfName}
        </Text>
      </div>
    )
  }

  const renderCpasIcon = (rowData: any) => {
    const { data } = rowData;
    return (<Popover content='初始化组成部分' placement="left">
      <div className={data.zcbfzt !== 1 ? 'hoverBac' : ''}>
        <CpasIcon type='icon-zhongzhipeizhi' color={data.zcbfzt !== 1 ? '' : '#ddd'} fontSize={16} onClick={async () => {
          if (data.zcbfzt !== 1) {
            await initializePopupRef.current.showInit(`'${data.zcbfid}'`, tableRow.XMType);
          }
        }}></CpasIcon>
      </div>
    </Popover>)
  };

  async function getConvertOnlineDataArray(): Promise<API.ConvertOnlineData[]> {
    await treeListRef.current.instance.saveEditData();
    const treeDataOfLocalZcbfid: any[] = treeData.filter((item: any) => item.localProjectDisplayText)
    return treeDataOfLocalZcbfid.map(item => {
      // debugger
      const onlinePart: API.ConvertPartInfo = {
        dbname: item.dbname,
        pzcbfID: item.pzcbfID,
        sjnd: item.sjnd,
        sjxmbh: item.sjxmbh,
        ssbm: item.ssbm,
        stack_status: item.stack_status,
        zcbfName: replaceFullSpace(item.zcbfName),//全角空格,
        zcbfid: item.zcbfid,
        zcbfzt: item.zcbfzt,
      }
      /*DBName,id,projectID,projectBh,projectName,sjxmbh,sjnd,projectState,
     * xmhhr,manager,quality,XMType,bsdw,xmTimeEnd,xmTimeStart
      */

      const localProject = localProjectList.find(item2 => item.localProjectDisplayText == item2.displayText);
      const localPart: API.ConvertPartInfo = {
        dbname: localProject.dbname || localProject.DBName || localProject.zcbfid,
        pzcbfID: '',
        sjnd: localProject.sjnd,
        sjxmbh: localProject.sjxmbh,
        ssbm: '',
        stack_status: '0',
        zcbfName: replaceFullSpace(localProject.zcbfName),//全角空格
        zcbfid: localProject.zcbfid,
        zcbfzt: localProject.projectState,
        xmType: localProject.xmType,
      }
      const retData = {
        projectCode: tableRow.sjxmbh || '',
        onlinePart,
        localPart,
      }
      return retData;
    })
  }
  /**
   * 单机转联机完成事件
   * @param isOk 
   */
  function onConvertToLineFinished(isOk: Boolean) {
    getZcbfListData(true);
    loadLocalProjectList();//加载单机项目列表
  }
  //获取分组数据源
  function getGroupedDataSource(ungroupedData: any[], key: string, groupBy: string) {
    if (!ungroupedData || ungroupedData.length == 0) return ungroupedData;
    const fromUngroupedData = new DataSource({
      store: {
        type: 'array',
        data: ungroupedData,
        key: key,
      },
      group: groupBy,
    });
    return fromUngroupedData;
  }
  return (
    <div style={{ height: '100%', width: '100%' }} className='treeListBox'>
      <TreeList
        className="PublicTreeList"
        ref={treeListRef}
        height='100%'
        keyExpr="zcbfid"
        parentIdExpr="pzcbfID"
        allowColumnReordering={true}
        allowColumnResizing={true}
        dataSource={treeData}
        autoExpandAll={true}
        showRowLines={true}
        showColumnLines={true}
        showBorders={true}
        // rowAlternationEnabled={true}
        columnResizingMode="widget"
        scrolling={{ rowRenderingMode: 'virtual' }}
        // rootValue=''
        hoverStateEnabled={true}
        columnMinWidth={100}
        //改为onCellDblClick by csb 20231105,因为要判断单机转联机里,选择单机项目的列是不能双击的
        onCellDblClick={async (e: CellDblClickEvent) => {
          if (showConvertOnline) {//单机转联机模式
            const { data, column } = e;
            if (data.zcbfzt && data.zcbfzt > 0) {
              if (column.dataField !== 'localProjectDisplayText') {//单机转联机选择列
                await dblClickSkip(data);
              }
            }
          }
        }}
        onRowDblClick={async (e: RowDblClickEvent) => {
          if (!showConvertOnline) {
            const { data } = e;
            if (data.zcbfzt && data.zcbfzt > 0) {
              await dblClickSkip(data);
            } else {
              notify({ message: `请先初始化`, position: 'top center' }, "warning", 1000);
            }
          }
        }}
        loadPanel={{ enabled: true }}
        searchPanel={{
          width: 100, visible: true,
          placeholder: '',
          searchVisibleColumnsOnly: true
        }}
        paging={{
          enabled: false
        }}
        rowAlternationEnabled={true}
      >
        <Toolbar>
          {/* 执行 单机转联机 */}
          <Item location="after" render={() =>
            <ConvertOnlineButton
              showConvertOnline={showConvertOnline}
              getConvertOnlineDataArray={getConvertOnlineDataArray}
              projectCode={tableRow.sjxmbh}
              projectName={tableRow.projectName}
              onFinished={onConvertToLineFinished}
              disabled={tableRow.XMType != "联机审计项目"}
            />}
          />

          <Item location="after" render={() => <Checkbox
            style={{ width: 110, padding: 0 }}
            checked={showConvertOnline}
            disabled={tableRow.XMType != "联机审计项目"}
            onChange={value => setShowConvertOnline(value.target.checked)}>转为联机</Checkbox>
          } />

          <Item location="after" name='searchPanel' />
          <Item location="after" render={() => <>
            <Button
              className="defaultReloadBtnWhite"
              render={() => (showSpin ? <LoadIndicator id="medium-indicator" height={16} width={16} /> :
                <CpasIcon type='icon-refresh' fontSize={16} />
              )}
              onClick={() => {
                getZcbfListData(true);
              }} />
          </>
          } />
        </Toolbar>

        <Column
          width={showConvertOnline ? 150 : 200}
          allowEditing={false}
          headerCellRender={() => (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'left' }}>
              <Checkbox
                className='handWritingCheckBox'
                style={{ margin: '0px  7px' }}
                indeterminate={treeDataMinate !== selectedRows.length && selectedRows.length !== 0}
                checked={treeDataMinate === selectedRows.length && treeDataMinate !== 0}
                onChange={(e: any) => {
                  e.stopPropagation();
                  const isChecked = e.target.checked;
                  let selectedID: any = [];
                  let selectedZcbfName: any = [];
                  if (isChecked) {
                    treeData.forEach((item: any) => {
                      if (item.zcbfzt === 1) {
                        selectedID.push(item.zcbfid);
                        selectedZcbfName.push(item.zcbfName);
                      }
                    });
                  } else {
                    selectedID = [];
                    selectedZcbfName = [];
                  }
                  setSelectedRows(selectedID);
                  setSelectedRowsName(selectedZcbfName);
                  onTableTreeSelection(selectedID, selectedZcbfName);
                }}
              />
              {intl('pro.TreeList.ComponentName', '组成部分编号')}
            </div>
          )}
          dataField='zcbfid'
          cellRender={(row: any) => {
            const { data } = row;
            return renderGridCell(data);
          }}
        />

        <Column
          caption='组成部分名称'
          dataField='zcbfName'
          allowEditing={false}
          cellRender={(row: any) => {
            const { data } = row;
            return renderGridCellName(data);
          }}
        />

        <Column
          caption='状态'
          dataField='zcbfzt'
          allowEditing={false}
          alignment={showConvertOnline ? 'left' : 'center'}
          width={showConvertOnline ? 50 : 80}
          allowSearch={false}
          cellRender={(row: any) => {
            //  0 没有初始化 1初始化正常  2 初始化失败 
            if (row.data.zcbfzt === 0) {
              return <span style={{ color: '#00A7B5' }}>未初始化</span>
            } else if (row.data.zcbfzt === 1) {
              return <span style={{ color: "#9FDD33" }}>正常</span>
            } else {
              return <span style={{ color: '#E92841' }}> 异常 </span>
            }
          }}
        />


        <Column
          width={100}
          allowSearch={false}
          caption={intl('pro.TreeList.Operation', '操作')}
          dataField='manager'
          alignment="center"
          fixed={true}
          fixedPosition='right'
          allowResizing={false}
          visible={!showConvertOnline}
          allowEditing={false}
          cellRender={(row: any) => (
            <div className='operationBox'>
              {renderCpasIcon(row)}
              <div className='hoverBac'>
                <CpasIcon type='icon-delete' fontSize={16} onClick={() => {
                  const { data } = row;
                  if (data.zcbfzt === 1) {
                    delButtonClick(data);
                  }
                }}></CpasIcon>
              </div>
            </div>
          )}
        />
        <Column
          width={200}
          allowSearch={true}
          caption={'关联审计项目'}
          dataField='localProjectDisplayText'
          alignment="left"
          allowResizing={false}
          visible={showConvertOnline}
          allowEditing={showConvertOnline && tableRow.XMType == "联机审计项目"}
          editorType='dxLookup' // 使用 Lookup 编辑器
          editorOptions={{
            //dataSource:  localProjectList , // 可选项数据源
            dataSource: getGroupedDataSource(localProjectList, 'zcbfid', 'groupName'),
            valueExpr: "displayText", // 数据项中用于值的字段
            displayExpr: "displayText", // 数据项中用于显示文本的字段
            placeholder: "选择审计项目", // 初始占位符文本
            closeOnOutsideClick: true, // 点击外部区域时关闭弹出窗口
            // showPopupTitle: true, // 显示弹出窗口标题
            //  label: "请选择单机项目", // 弹出窗口标题文本
            searchEnabled: true, // 启用搜索功能
            showClearButton: true,
            showDropDownButton: true,
            grouped: true,
            dropDownOptions: {
              minWidth: 300,
              width: 600,
            }
          }}
        /*   customizeText={((data: any) => {
          return replaceFullSpace(data.ValueText);//替换全角替换,不能用,显示不lookup不出来
        })} */
        />
        <Editing
          allowAdding={false}
          allowUpdating={showConvertOnline}
          allowDeleting={false}
          mode="cell" />
        {/* <Paging defaultPageSize={5} /> */}
      </TreeList>
      <InitializePopup ref={initializePopupRef} initData={{ popupTitle: 'zcbf' }} closeAndReload={() => getZcbfListData()} />
      <InputOKDialog ref={refsInputDialog} refreshTable={() => {
        getZcbfListData();
        if (tableRow.XMType === "单机审计项目") {
          PubSub.publish('projectTreeRefresh', { msg: 'projectRefresh' });
        }
      }} />
    </div >
  );
});

export default ZcbfTreeList;
